package com.favorite;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

public class Solution1584 {
    int[] father;
    public int minCostConnectPoints(int[][] points) {
        father = new int[points.length];
        for (int i = 0; i < points.length; i++) {
            father[i] = i;
        }
        PriorityQueue<int[]> priorityQueue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o1[2], o2[2]);
            }
        });
        for (int i = 0; i < points.length; i++) {
            for (int j = i + 1; j < points.length; j++) {
                int dist = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
                priorityQueue.add(new int[]{i, j, dist});
            }
        }
        int res = 0;
        int count = 0;
        while (count < points.length - 1 && !priorityQueue.isEmpty()) {
            int[] ints = priorityQueue.poll();
            int i = ints[0];
            int j = ints[1];
            int dist = ints[2];
            if (!same(i, j)) {
                join(i, j);
                res += dist;
                count++;
            }
        }
        return res;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
